import { useState, useEffect } from 'react'
import { getStuList, deleteStuByIdApi } from '../api/stuApi'
import { useNavigate, useLocation } from 'react-router-dom'
import Alert from './Alert'
import './home.scss'

const Home = () => {
  console.log('Home 组件渲染')

  const navigator = useNavigate()
  const location = useLocation()

  const colums = [
    {
      label: '名称',
      key: 'name'

    },
    {
      label: '年龄',
      key: 'age'
    },
    {
      label: '手机号',
      key: 'phone'
    },
    {
      label: '邮箱',
      key: 'email'
    },
    {
      label: '操作',
      key: 'action'
    }
  ]
  const [tableData, setTableData] = useState([])
  // 修改状态管理
  const [alertMessage, setAlertMessage] = useState()

  useEffect(() => {
    console.log('Home 组件挂载')
    getStuList().then(res => {
      setTableData(res.data)
    })
  }, [])

  useEffect(() => {
    console.log('location 改变，但组件没有重新挂载')
    if (location.state?.msg) {
      setAlertMessage(location.state.msg)
    } else {
      setAlertMessage(null)
    }
  }, [location])

  // 刷新
  const refresh = async () => {
    const res = await getStuList();
    setTableData(res.data)
  }
  // 删除
  const deleteStu = async (id) => {
    await deleteStuByIdApi(id)
    refresh()
  }

  const btnItem = () => {
    return (
      <div className="btnItem">
        <button className="btn btn-primary " onClick={refresh} >刷新</button>
      </div>
    )
  }




  return (
    <div className="container">
      {alertMessage && (
        <Alert
          msg={alertMessage}
        />
      )}
      {btnItem()}
      <table className="table table-striped table-bordered">
        <thead>
          <tr>
            {colums.map(re => {
              return (
                <th scope="col" key={re.key}>{re.label}</th>
              )
            })}
          </tr>
        </thead>
        <tbody>
          {tableData.map((rem, index) => {
            return (
              <tr key={index}>
                <th scope="row">{index + 1}</th>
                <td>{rem.name}</td>
                <td>{rem.age}</td>
                <td>{rem.phone}</td>
                <td>{rem.email}</td>
                <td>
                  <button className="btn btn-primary" onClick={() => {
                    navigator(`/add/${rem.id}`)
                  }}>编辑</button>

                  <button style={{ marginLeft: '10px' }} onClick={() => deleteStu(rem.id)} className="btn btn-danger" >删除</button>

                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

export default Home